package cn.itcasa.service.impl;
import cn.itcasa.pojo.ItemDoc;
import cn.itcasa.pojo.RequestParams;
import cn.itcasa.service.SearchService;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.common.Client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
       private ItemClient itemClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 搜索自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestion(String prefix) {
        //1-创建请求对象
        SearchRequest request = new SearchRequest("item");
        //2-创建dsl语句
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "my_suggestion", SuggestBuilders.completionSuggestion("suggestion")
                        .skipDuplicates(true)
                        .size(10)
                        .prefix(prefix)
        ));
        //3-发起请求

        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //4-解析结果
        CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");
        ArrayList<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
            Text text = option.getText();
            list.add(text.toString());

        }
        return list;


    }

    /**
     * 聚合条件查询
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> search(RequestParams params) {
        // 1-创建request对象
        SearchRequest request = new SearchRequest("item");
        // 2-创建dsl语句
        request.source().size(0);
        // 3-构建query对象
        Query(params, request);

        // 4-聚合条件
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("categoryAgg").field("category").size(20)
        );
        //5-发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //6-解析结果封装返回数据
        Map<String, List<String>> map = new HashMap<>();
        Terms brandAgg = response.getAggregations().get("brandAgg");
        ArrayList<String> buckelist = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            String bucketKey = bucket.getKeyAsString();
            buckelist.add(bucketKey);
        }
        map.put("brand", buckelist);
        Terms categoryAgg = response.getAggregations().get("categoryAgg");
        ArrayList<String> categorylist = new ArrayList<>();
        for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
            String category = bucket.getKeyAsString();
            categorylist.add(category);
        }
        map.put("category", categorylist);


        return map;
    }

    /**
     * 基本查询
     *
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> searchAll(RequestParams params) {
        // 1-创建request对象
        SearchRequest request = new SearchRequest("item");
        // 2-创建dsl语句
        // 3-构建query对象
        Query(params, request);
        int page = params.getPage();
        int size = params.getSize();
        // 分页
        request.source().from((page - 1) * size).size(size);
        //排序
        String sortBy = params.getSortBy();
        if ("price".equals(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        } else if ("sold".equals(sortBy)) {
            request.source().sort("sold", SortOrder.DESC);
        }
        // 高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false)
                .preTags("<span style='color:green'>").postTags("</span>"));//高亮颜色请自定义我选择了你最爱的绿色~~~
        //5-发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SearchHits responseHits = response.getHits();

        long total = responseHits.getTotalHits().value;
        ArrayList<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : responseHits.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            //fastJso将字符串转java对象
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0) {
                String name = highlightFields.get("name").toString();
                itemDoc.setName(name);
            }
            list.add(itemDoc);
        }


        return new PageDTO<>(total, list);
    }

    /**
     * 根据id新增一条数据
     *
     * @param id 商品id
     */
    @Override
    public void insterItemById(Long id) {
        //1-先获取商品信息
        Item item = itemClient.queryItemById(id);

        ItemDoc itemDoc = new ItemDoc(item);
        //2-准备request
        IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
        //3-准备dsl
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        //4-发送请求
        try {
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 根据id删除一条数据
     *
     * @param id 商品id
     */
    @Override
    public void deleteItemById(Long id) {
        //1准备request
        DeleteRequest request = new DeleteRequest("item", id.toString());
        //2发送请求
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private void Query(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //StringUtils.isNotEmpty(" ") = true//如果是空格的字符，仍然判断为true
        //StringUtils.isNotBlank("") = false
        if (StringUtils.isNotBlank(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (StringUtils.isNotBlank(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            // 价格区间查询(注意单位为分)
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice() * 100)
                    .lte(params.getMaxPrice() * 100));
        }
        //广高置顶（根据权重）
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );
        request.source().query(queryBuilder);
    }




}
